﻿//分页方法
var mylist = new Object();
var upload_img = "";
var www_img = "";
function loadPage(total, pagesize, pageno) {
    mylist = new TurnPage("mylist");
    mylist.pageSize = pagesize;
    mylist.currPage = pageno;
    mylist.total = total;
    mylist.callback = function () {

        location.href = GetPageUrl(location.href, mylist.currPage, mylist.total, mylist.pageSize);

    };
    $("#pager").html(mylist.getOutput());
    $(":input[name=ckId_t]").click(function () {
        if (this.checked) {
            $(":input[name=ckId]").attr("checked", "true");
            return;
        }
        else {
            $(":input[name=ckId]").removeAttr("checked");
        }
    });
}

$.ajaxSetup({
    global: true,
    beforeSend: function () {//loadingLayer.show("正在向服务器提交请求");
    },
    complete: function () {//loadingLayer.close();
    }

});
function GetPageUrl(url, pageno, total, pagesize) {
    var strHref = url;
    var intPos = strHref.indexOf("?");
    var strRight = strHref.substr(intPos + 1);
    var arrTmp = strRight.split("&");
    var pre = (url.indexOf("?") == -1) ? url : url.substring(0, url.indexOf("?"));
    pre += "?";
    for (var i = 0; i < arrTmp.length; i++) {
        var paraTemp = arrTmp[i].split("=");
        if (paraTemp[0].toLowerCase() == "pageno")
            pre += "&" + paraTemp[0].toLowerCase() + "=" + pageno;
        else if (paraTemp[1] != undefined)
            pre += "&" + paraTemp[0].toLowerCase() + "=" + paraTemp[1];
    }
    if (pre.toLowerCase().indexOf("pageno") < 0) {
        pre += "&pageno=" + pageno;
    }
    if (pre.toLowerCase().indexOf("total") < 0) {
        pre += "&total=" + total;
    }
    if (pre.toLowerCase().indexOf("pagesize") < 0) {
        pre += "&pagesize=" + pagesize;
    }

    return pre;
}

//获取URL参数值
function GetQueryString(name, url) {
    if (!url)
        url = window.location.href;
    var reg = new RegExp("(/?|&)" + name + "=([^&]*)(&|$)");
    var r = url.match(reg);
    if (r != null) return decodeURIComponent(r[2]).replace(/</g, "&lt;").replace(/>/g, "&gt;");
    else return null;
}
function clearForm() {
    $("#mForm :input[type!=button]").val("");
    $.each($("#mForm :input[vinit]"), function (i, o) {
        $(o).val($(o).attr("vinit"));
    });
    if ($("#edit")) {
        $("#edit").src = "/edit.htm?" + (new Date()).getTime();
    }
    $("#pic").empty();

}
//页面公用事件实现
$(document).ready(function () {
    //表单清空
    $(":input[name=btnClear]").click(function () {
        clearForm();
    });

    //全选
    $(":input[name=Id_t]").click(function () {
        if (this.checked) {
            $(":input[name=ckId]").attr("checked", "ture");
            return;
        }
        else {
            $(":input[name=ckId]").removeAttr("checked");
        }
    });
});


//swfupload
function createUpload(placeholder, progressTarget, cancelButtonId, success, areaId) {
    var file_size = arguments[5] ? arguments[5] : "200";

    var upload = new SWFUpload({
        upload_url: upload_img + "/Upload/uploadcmspic.html",
        post_params: { "userid": 54 },

        // File Upload Settings

        file_size_limit: file_size, // 100MB
        file_types: "*.*",
        file_types_description: "All Files",
        file_upload_limit: "10",
        file_queue_limit: "0",

        // Event Handler Settings (all my handlers are in the Handler.js file)
        file_dialog_start_handler: fileDialogStart,
        file_queued_handler: fileQueued,
        file_queue_error_handler: fileQueueError,
        file_dialog_complete_handler: fileDialogComplete,
        upload_start_handler: uploadStart,
        upload_progress_handler: uploadProgress,
        upload_error_handler: uploadError,
        upload_success_handler: typeof (success) == "string" ? uploadSuccess : success,
        upload_complete_handler: uploadComplete,

        // Button Settings
        button_image_url: "/Scripts/swfupload/XPButtonUploadText_61x22.png",
        button_placeholder_id: placeholder,
        button_width: 61,
        button_height: 22,

        // Flash Settings
        flash_url: "/Scripts/swfupload/swfupload.swf",


        custom_settings: {
            progressTarget: progressTarget,
            cancelButtonId: cancelButtonId,
            areaId: typeof (success) == "string" ? success : areaId
        },

        // Debug Settings
        debug: false
    });
}
function insertUploadHtml(url, jo, len) {
    url = url.replace(/\"/g, "");
    var _url = www_img + "/" + url;
    var ext = url.substring(url.lastIndexOf(".") + 1);
    switch (ext) {
        case "jpg":
        case "jpeg":
        case "png":
        case "gif":
        case "bmp":
            jo.val(jo.val().substring(0, len) + '<img src="' + _url + '"/>' + jo.val().substring(len));
            break;
        case "swf":
            var swfhtml = '<object align="middle" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" id="Untitled-1">\
                                 <param name="allowScriptAccess" value="sameDomain"/>\
                                 <param name="movie" value="/css/ad/wwwqt2288com.swf"/>\
                                 <param name="quality" value="high"/>\
                                 <param name="bgcolor" value="#ffffff"/>\
                                 <embed align="middle" src="' + _url + '" quality="high" bgcolor="#ffffff" name="mymovie" allowscriptaccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"/>\
                                 </object>';
            jo.val(jo.val().substring(0, len) + swfhtml + jo.val().substring(len));
            break;
        case "flv":
            var flvhtml = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab #version=6,0,29,0" width="440px" height="400px">\
            <param name="movie" value="' + www_img + '/20113/Flvplayer.swf?"' + _url + '"/>\
            <param name="quality" value="high"/>\<param name="allowFullScreen" value="true" />\
            <embed src="' + www_img + '/20113/Flvplayer.swf?vcastr_file="' + _url + '" allowFullScreen="true" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="240" height="180"></embed>\
            </object>';
            jo.val(jo.val().substring(0, len) + flvhtml + jo.val().substring(len));
            break;
        default:
            jo.val(jo.val().substring(0, len) + '<img src="' + _url + '"/>' + jo.val().substring(len));
    }
}

//传入url，填充入已上传文件
function uploadCallback(url, areaid, picid, pictitle) {
    if (!areaid)
        areaid = "pic";
    if (areaid.indexOf("ins_") > -1) {
        var jo = $(":input[name=" + $("#" + areaid).attr("vtar") + "]");
        return insertUploadHtml(url, jo, _len[jo.attr("name")]);
    }
    if (!url)
        return;
    if (!picid)
        picid = "";
    if (!pictitle)
        pictitle = "";
    url = url.replace(/\"/g, "");
    var _url = www_img + "/" + url;
    var ext = url.substring(url.lastIndexOf(".") + 1);
    //var _html = '<input type=button name="inp_uploads" vid="'+picid+'" vurl="' + url + '" value=" <<< delete" onclick="delUpload(this,\'' + url + '\')"/>';
    //2010-11-26 增加标题
    var _html = ' 标题：<input type="text" name="inp_title" MaxLength="500" value="' + pictitle + '" vid="' + picid + '" size="15"/>';
    _html += ' <input type=button name="inp_uploads" vid="' + picid + '" vurl="' + url + '" value=" <<< delete" onclick="delUpload(this,\'' + url + '\')"/>';
    switch (ext) {
        case "jpg":
        case "jpeg":
        case "png":
        case "gif":
        case "bmp":
            $("#" + areaid).append("<p>" + "<img  src='" + _url + "'/>" + _html + "</p><span class='tsxx'></span>");
            break;
        default:
            $("#" + areaid).append("<p>" + "<a target='_blank' href='" + _url + "'>" + _url + "</a>" + _html + "</p><span class='tsxx'></span>");
    }
}




//删除文件
function delUpload(o, url) {
    $.getJSON(upload_img + "/upload/deleteSellersPic.html?picid=" + $(o).attr("vid") + "&path=" + url + "&jsoncallback=?", function (data) {
    });
    $(o).parent().next("span").remove();
    $(o).parent().remove(); //回调不执行?
}

//获取上传的文件地址，以分号分隔
function getUploadUrls(areaid) {
    var pics = [];
    if (!areaid)
        areaid = "pic";
    var url = "";
    $.each($("#" + areaid + " :input[name=inp_uploads]"), function (i, o) {
        pics.push({ url: $(o).attr("vurl"), id: $(o).attr("vid"), title: $(o).prev(":input[name=inp_title]").val() });
    });
    if (pics.length == 0)
        pics.push({ url: '', id: '', title: '' });
    return pics;
}


//获取子站信息，chenjing 2010-10-9 
function initsubsite(chbox_name) {
    $.post("/cms/getSubsite.html", null, function (dta) {
        dta = $.evalJSON(dta);
        var obj = $(":input[name=" + chbox_name + "]");
        var _name_first = "";
        $.each(dta, function (i, o) {
            o.n = o.n.replace(/\[\w+\.(.+)\.\w+\]/g, " <font class='no'>[ $1 ]</font>");
            if (_name_first != o.n.substring(0, 1)) {
                _name_first = o.n.substring(0, 1);
                obj.parent().append('<p/>');
            }
            obj.parent().append('<input name="' + chbox_name + '" value="' + o.v + '" type="checkbox" id="' + chbox_name + i + '"><label for="' + chbox_name + i + '" title="">' + o.n + '</label>  ');

        });
        obj.remove();
        //$.fillItem(dta,chbox_name);
        var _all = "ch_" + chbox_name;
        $(":checkbox[name=" + _all + "]").click(function () {
            if (this.checked) { $(":checkbox[name=" + chbox_name + "]").attr("checked", "checked"); }
            else { $(":checkbox[name=" + chbox_name + "]").removeAttr("checked"); }
        });
        $(":checkbox[name=" + chbox_name + "]").click(function () {
            if (!this.checked) { $(":checkbox[name=" + _all + "]").removeAttr("checked"); }
        });
        var arr = window.parent.location.href.match(/.*\/(\d+)/);
        if (arr)
            $.each($(":checkbox[name=" + chbox_name + "]"), function (i, o) {
                if ($(o).val() == arr[1]) {
                    $(o).attr("checked", "checked");
                    $(o).attr("vchecked", "true");
                    $(o).addClass("red");
                }
            });
    });
}

//对约定命名的显示初始化,cms采编专用
function initview() {
    //约定重置按钮名：buttReset ；提交按钮名： buttEdit； 表单区域id : mainForm ；行编辑链接名： linkEdit
    $("input[name='buttReset']").click(function () {
        $("#mainForm caption").html("新增数据");
        $("#mainForm th").html("新增数据");
        $("input[name='buttEdit']").val("新增");
        $("#mainForm :input[type!=button][type!=checkbox][type!=radio]").val('');
        $("#mainForm :checkbox").removeAttr("checked");
        $.each($("#mainForm :input[vseek]"), function (i, o) {
            $(o).val($(this).attr("vseek"));
            $(o).css("color", "grey");
            $(o).click(function () {
                if ($(o).val() == $(o).attr("vseek"))
                    $(o).val("");
            });
            if (GetQueryString("seektags")) {
                regular_input.sourceid = { exp: /^[1-9]\d*$/, m: "请选择匹配的标签" }
                $(o).autocomplete(tags, {
                    minChars: 0,
                    width: 310,
                    matchContains: true,
                    autoFill: false,
                    formatItem: function (row, i, max) {
                        return i + "/" + max + ": \"" + row.name + "\" [" + row.id + "]";
                    },
                    formatMatch: function (row, i, max) {
                        return row.name + " " + row.id;
                    },
                    formatResult: function (row) {
                        return row.name;
                    }
                });
                $(o).result(function (event, data, formatted) {
                    $(":input[name=sourceid]").val(data.id);
                });
                $(o).blur(function () { $.checkInputValid($(":input[name=sourceid]")[0]) });

            }
            if (GetQueryString("seekarea")) {
                regular_input.sourceid = { exp: /^[1-9]\d*$/, m: "请选择匹配的商圈" };
                var area;
                $.post("/baseparam/getTradearea.html", null, function (dta) {
                    area = $.evalJSON(dta);
                    $(o).autocomplete(area, {
                        minChars: 0,
                        width: 310,
                        matchContains: true,
                        autoFill: false,
                        formatItem: function (row, i, max) {
                            return i + "/" + max + ": \"" + row.name + "\" [" + row.id + "]";
                        },
                        formatMatch: function (row, i, max) {
                            return row.name + " " + row.id;
                        },
                        formatResult: function (row) {
                            return row.name;
                        }
                    });
                });
                $(o).result(function (event, data, formatted) {
                    $(":input[name=sourceid]").val(data.id);
                });
                $(o).blur(function () { $.checkInputValid($(":input[name=sourceid]")[0]) });

            }
            /*$(this).blur(function(){
            if($.trim($(this).val()) == "")
            $(this).val($(this).attr("vseek"));
            else{
				
            }
            });*/

        });
        $.each($("#mainForm :input[vinit]"), function (i, o) {
            $(this).val($(this).attr("vinit"));
        });
        $.each($("#mainForm :checkbox[vchecked],:radio[vchecked]"), function (i, o) {
            $(this).attr("checked", "checked");
        });
        $.each($("#seekForm :input[vinit]"), function (i, o) {
            $(this).val($(this).attr("vinit"));
        });
    })
    $("input[name='buttReset']").click();
    $("a[name=linkEdit]").click(function () {
        $("#mainForm caption").html("修改数据");
        $("#mainForm th").html("修改数据");
        $("input[name='buttEdit']").val("修改");
    });
    if (GetQueryString("s_upload")) {
        $("#s_upload").css("display", "");
        $("#s_upload p.ti").html(GetQueryString("s_upload"));
    }
    if (GetQueryString("s_title1")) {
        $("#s_title1 p.ti").html(GetQueryString("s_title1"));
    }
    if (GetQueryString("s_title2")) {
        $("#s_title2").css("display", "");
        $("#s_title2 p.ti").html(GetQueryString("s_title2"));
    }
    if (GetQueryString("s_title3")) {
        $("#s_title3").css("display", "");
        $("#s_title3 p.ti").html(GetQueryString("s_title3"));
    }
    if (GetQueryString("s_title4")) {
        $("#s_title4").css("display", "");
        $("#s_title4 p.ti").html(GetQueryString("s_title4"));
    }
    if (GetQueryString("s_upload_file")) {
        $("#s_upload_file").css("display", "");
        $("#s_upload_file p.ti").html(GetQueryString("s_upload_file"));
    }
    if (GetQueryString("linkurl1")) {
        $("#linkurl1 p.ti").html(GetQueryString("linkurl1") + "（选填,可以是“http://admin.meidaokeji.com/cms/index.html”或“/cms/index.html”）：");
    }
    if (GetQueryString("linkurl2")) {
        $("#linkurl2").css("display", "");
        $("#linkurl2 p.ti").html(GetQueryString("linkurl2") + "（选填,可以是“http://admin.meidaokeji.com/cms/index.html”或“/cms/index.html”）：");
    }
    if (GetQueryString("linkurl3")) {
        $("#linkurl3").css("display", "");
        $("#linkurl3 p.ti").html(GetQueryString("linkurl3") + "（选填,可以是“http://admin.meidaokeji.com/cms/index.html”或“/cms/index.html”）：");
    }
    if (GetQueryString("unescape")) {
        var arr = GetQueryString("unescape").split(",");
        $.each(arr, function (i, n) {
            $("#mainForm :input[name=" + n + "]").attr("escape", "false");
        });
    }

    //列表全选，约定每行checkbox名id。全选框名ch_id
    $(":checkbox[name=ch_id]").click(function () {
        if (this.checked) { $(":checkbox[name=id]").attr("checked", "checked"); }
        else { $(":checkbox[name=id]").removeAttr("checked"); }
    });
    $(":checkbox[name=id]").click(function () {
        if (!this.checked) { $(":checkbox[name=ch_id]").removeAttr("checked"); }
    });
    //行变更自动选择checkbox
    $("#mainTable :input").change(function () {
        var id = $(this).attr("vid");
        if (id)
            $(":checkbox[name=id][value=" + id + "]").attr("checked", "checked");
    });
    $("#opeTable input[name=section]").mouseover(function () {
        if (this.value != "") {
            var reg = new RegExp("http:\/\/.*([\?]|&)sectioncode=([^&]*)(&|$)");
            var r = this.value.match(reg);
            if (r != null) {
                var _limit = GetQueryString("limit", this.value);
                var _attr = $(this).attr("vlimit");
                if (_limit && _attr && _limit != _attr) {
                    alert("推送到不匹配的栏目！");
                    this.value = "";
                }
                else
                    this.value = unescape(r[2]);
            }
            else if (this.value.match(/http:\/\//)) {
                this.value = "";
                alert("错误！请拖拽左边菜单【网站栏目采编】下的栏目");
            }
        }
    });
    $("#mainForm :input").change(function () {
        if (!$.checkInputValid(this)) return;
    });
    if (typeof ($.datepicker) != "undefined") {
        $(':text.date').datepicker({
            duration: '',
            showTime: false,           //日期控件是否显示时间
            constrainInput: false,
            stepMinutes: 1,
            stepHours: 1,
            altTimeField: '',
            changeMonth: true,
            changeYear: true,
            time24h: true  //是否是24h制
        });
        $(':text.time').datepicker({
            duration: '',
            showTime: true,           //日期控件是否显示时间
            constrainInput: false,
            dateFormat: "yy-mm-dd",
            stepMinutes: 1,
            stepHours: 1,
            altTimeField: '',                                            
            changeMonth: true,
            changeYear: true,
            time24h: true  //是否是24h制
        });
        $(':text.year').datepicker({
            duration: '',
            showTime: false,           //日期控件是否显示时间
            changeMonth: true,
            changeYear: true,
            monthNamesShort: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
            yearRange: '1950:2012'
        });
    }
}

function getsubsite() {
    var sites = "";
    $.each($("input[name=subsite]"), function (i, o) {
        if (o.checked)
            sites += sites == "" ? o.value : "," + o.value;
    });
    return sites;
}
$.fn.extend({
    position1: function (value) {
        var elem = this[0];
        if (elem && (elem.tagName == "TEXTAREA" || elem.type.toLowerCase() == "text")) {
            if ($.browser.msie) {
                var rng;
                if (elem.tagName == "TEXTAREA") {
                    rng = event.srcElement.createTextRange();
                    rng.moveToPoint(event.x, event.y);
                } else {
                    rng = document.selection.createRange();
                }
                if (value === undefined) {
                    rng.moveStart("character", -event.srcElement.value.length);
                    return rng.text.length;
                } else if (typeof value === "number") {
                    var index = this.position1();
                    index > value ? (rng.moveEnd("character", value - index)) : (rng.moveStart("character", value - index))
                    rng.select();
                }
            } else {
                if (value === undefined) {
                    return elem.selectionStart;
                } else if (typeof value === "number") {
                    elem.selectionEnd = value;
                    elem.selectionStart = value;
                }
            }
        } else {
            if (value === undefined)
                return undefined;
        }
    }
})  

